package chen.yi.common.resp;

import chen.yi.common.enums.RespEnum;
import chen.yi.component.log.utils.ThreadMdcUtil;
import lombok.Getter;

import java.io.Serializable;

/**
 * 统一返回出参
 * @author huat
 **/
@Getter
public final class R<T> implements Serializable {

    private final int code; //状态码
    private final String message;//提示信息
    private final T data; //返回数据
    private final boolean success;//是否执行成功
    private final String traceId;//traceId

    private R(int code, String message, T data, boolean success) {
        this.code = code;
        this.message = message;
        this.data = data;
        this.success = success;
        this.traceId = ThreadMdcUtil.getTraceId();
    }

    private R(int code, String message, boolean success) {
        this(code, message,null,success);

    }

    private R( int code,String message) {
        this(code,message,true);

    }

    /**
     * 执行成功无返回内容
     * @return 统一返回对象
     */

    public static R<?> success() {
        return new R<>(RespEnum.SUCCESS.getCode(),RespEnum.SUCCESS.getMessage());
    }
    /**
     * 执行成功有返回内容
     * @return 统一返回对象
     */
    public static <T> R<T> success(T t) {
        return new R<>(RespEnum.SUCCESS.getCode(),RespEnum.SUCCESS.getMessage(),t,true);
    }
    /**
     * 自定义执行成功状态码
     * @param respEnum 响应枚举值
     * @return 统一返回对象
     */
    public static <T> R<?> success(RespEnum respEnum) {
        return new R<>(RespEnum.SUCCESS.getCode(),RespEnum.SUCCESS.getMessage());
    }

    /**
     * 执行失败
     * @return 统一返回对象
     */
    public static R<?> error(){
        return new R<>(RespEnum.ERROR.getCode(),RespEnum.ERROR.getMessage(),false);
    }
    /**
     * 执行失败
     * @return 统一返回对象
     */
    public static R<?> error(String message) {
        return new R<>(RespEnum.ERROR.getCode(),message,false);
    }
    /**
     * 执行失败
     * @return 统一返回对象
     */
    public static R<?> error(RespEnum respEnum) {
        return new R<>(respEnum.getCode(),respEnum.getMessage(),false);
    }
}
